package com.tinem.platform.service.message.observable;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.mail.MailAccount;
import com.alibaba.fastjson.JSONObject;
import com.tinem.platform.module.pojo.enums.message.PushChannel;
import com.tinem.platform.module.pojo.vo.message.PushReq;
import com.tinem.platform.module.starter.web.context.GatewayContext;
import com.tinem.platform.service.message.config.ClientConfiguration;
import com.tinem.platform.service.message.config.MailConfiguration;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.mail.DefaultAuthenticator;
import org.apache.commons.mail.HtmlEmail;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @author fzh
 * @version v1
 * @program: platform
 * @className EMailListener
 * @description TODO
 * @site 
 * @company 
 * @create 2020-09-28 17:55
 */
@Slf4j
@Service
@Order(100)
public class EMailListener implements ApplicationListener<MessageObservable> {

    @Resource
    MailConfiguration mailConfiguration;

    @Resource
    ClientConfiguration clientConfiguration;

    @SneakyThrows
    @Override
    public void onApplicationEvent(MessageObservable event) {
        if(!event.getSource().getPushChannel().equals(PushChannel.EMAIL)){
            return;
        }
        if(!(event.getBody() instanceof String)){
            return;
        }
        PushReq pushReq = event.getSource();

        // 获取客户端配置邮件账户
        ClientConfiguration.Config config = clientConfiguration.getConfig().get(GatewayContext.getClient());
        MailAccount mailAccount = null;
        //如果渠道配置发送方。则必须使用渠道发送方
        if(StrUtil.isNotEmpty(config.getEmail())){
            mailAccount = mailConfiguration.getSendAccounts().get(config.getEmail());
        }else{
            //如果请求发送方在配置中存在，则使用请求发送方
            mailAccount = mailConfiguration.getSendAccounts().get(pushReq.getFrom());
            if(mailAccount == null){
                //使用默认发送方
                mailAccount = mailConfiguration.getSendAccounts().get(mailConfiguration.getMaster());
            }
        }

        HtmlEmail email= new HtmlEmail();
        email.setHostName(mailAccount.getHost());
        email.setSmtpPort(mailAccount.getPort());
        email.setStartTLSEnabled(mailAccount.isStarttlsEnable());
        email.setAuthenticator(new DefaultAuthenticator(mailAccount.getUser(), mailAccount.getPass()));
        email.setFrom(StrUtil.isNotEmpty(pushReq.getFrom())?pushReq.getFrom():mailAccount.getFrom());
        email.setSubject(pushReq.getExtMailSubject());
        email.setHtmlMsg((String) event.getBody());
        email.setCharset(StandardCharsets.UTF_8.displayName());
        email.addTo(pushReq.getTo());
        email.setDebug(mailAccount.isDebug());

        if(log.isDebugEnabled()){
            log.info("send email: "+JSONObject.toJSONString(mailAccount));
        }

        if(StrUtil.isNotEmpty(pushReq.getExtMailCc())){
            email.addCc(pushReq.getExtMailCc());
        }
        if(StrUtil.isNotEmpty(pushReq.getExtMailBcc())){
            email.addBcc(pushReq.getExtMailBcc());
        }
        email.send();
    }
}
